"""
Case Type   : 人为因素
Case Name   : gsql导入过程中，执行ctrl+c
Create At   : 2020/10/12
Owner       : @peilinqian
Description :
    1、执行gsql导入数据
    2、导入过程中执行ctrl+c（kill -2）
    3、重新执行第1步
Expect      :
    1、导入失败
    2、返回值正常，因为导入被中断所以整体耗时较短或ERROR:canceling statement due to user request
    3、导入成功
History     :
    2020/11/23 modified by @peilinqian :增加ctl+c返回user request的情况
    2020/12/08 modified by @peilinqian :gsql -f 需要多次ctl+c才能终止，增加5次循环保证进程被终止
    2021/03/17 modified by @peilinqian :完善断言信息
"""
import unittest
from yat.test import Node
import time
from yat.test import macro
import sys
import os

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *
from testcase.utils.ComThread import ComThread

logger = Logger()
common = Common('PrimaryRoot')
commonshpri = CommonSH('PrimaryDbUser')

class ModifyConnection(unittest.TestCase):
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    dbPrimaryRootNode = Node(node='PrimaryRoot')
    dbStandby1RootNode = Node(node='Standby1Root')
    DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
    DB_ENV_PATH = macro.DB_ENV_PATH
    Constant = Constant()
    dump_file_name = os.path.join(macro.DB_INSTANCE_PATH, 'reliability_humanfactor005.sql')

    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info("-----------this is setup-----------")
        logger.info("-----------reliability_humanfactor005 start-----------")
        logger.info("-----------dump success--------------------")
        result = commonshpri.dumpFile(self.dump_file_name, '-F p')
        logger.info(result)
        flag = 'dump database ' + self.dbPrimaryUserNode.db_name + ' successfully'
        self.assertIn(flag, result)

    def test_modify_pidfile(self):
        logger.info("-----------gsql restore--------------------")
        gsql_thread = ComThread(commonshpri.gsql_restore, args=(self.dump_file_name,))
        gsql_thread.start()
        time.sleep(5)

        logger.info("-----------ctl+c--------------------")
        for i in range(5):
            common.kill_pid_keyword(self.dump_file_name, '2', self.dbPrimaryUserNode)


        logger.info("-----------gsql fail--------------------")
        gsql_thread.join(int(macro.TPCC_RUN_MAX_TIME) * 2)
        result_thread = gsql_thread.get_result()
        spend_time_lines = result_thread.strip().splitlines()
        spend_time = spend_time_lines[-1].strip().split()
        logger.info(spend_time)
        return_flag = False
        # ctl+c中断结果1：返回值正常，因为导入被中断所以整体耗时较短
        # 结果2：ERROR:canceling statement due to user request'
        if spend_time[2].isnumeric():
            fail_spend_time = int(spend_time[2])
        elif 'canceling statement due to user request' in result_thread \
                or 'Cancel' in result_thread:
            return_flag = True
        else:
            logger.info("ctl+c 异常，请检查结果")
            self.assertTrue(False)

        time.sleep(10)

        logger.info("-----------gsql success--------------------")
        result = commonshpri.gsql_restore(self.dump_file_name)
        spend_time_lines = result.strip().splitlines()
        spend_time = spend_time_lines[-1].strip().split()
        logger.info(spend_time)
        if return_flag:
            if spend_time[2].isnumeric():
                self.assertTrue(True)
            else:
                self.assertTrue(False)
        elif spend_time[2].isnumeric() and not return_flag:
            success_spend_time = int(spend_time[2])
            self.assertTrue(success_spend_time > fail_spend_time)
        else:
            logger.info("ctl+c 异常，请检查结果")
            self.assertTrue(False)

    def tearDown(self):
        logger.info('----------------this is tearDown-----------------------')
        logger.info('----------------delete dump file-----------------------')
        cmd = 'rm -rf ' + self.dump_file_name
        self.dbPrimaryRootNode.sh(cmd)
